import { defineComponent, ref, computed, onMounted, watch } from "vue";
import { Row, Col, Spin, Tree, Popover, Space, Image } from "ant-design-vue";
import { useRouter, useRoute } from "vue-router";
import { user } from "@/api";
import { useUserStore, useSystemStore } from "@/stores";
import { studyTimeFormat } from "@/utils";
import CoursesModel from "./components/CoursesModel";
import Empty from "@/components/Empty";
import styles from "./index/index.module.scss";
import myLesoon from "@/assets/images/commen/icon-mylesoon.png";
import studyTime from "@/assets/images/commen/icon-studytime.png";
import iconRoute from "@/assets/images/commen/icon-route.png";
import defaultThumb1 from "@/assets/thumb/thumb1.png";
import defaultThumb2 from "@/assets/thumb/thumb2.png";
import defaultThumb3 from "@/assets/thumb/thumb3.png";

type StatsModel = {
  learn_duration: number;
  nun_required_course_count: number;
  nun_required_finished_course_count: number;
  nun_required_finished_hour_count: number;
  nun_required_hour_count: number;
  required_course_count: number;
  required_finished_course_count: number;
  required_finished_hour_count: number;
  required_hour_count: number;
  today_learn_duration: number;
};

type LearnCourseRecordsModel = {
  [key: number]: CourseRecordModel;
};

type CategoryModel = {
  key: number;
  title: any;
  children?: CategoryModel[];
};

export default defineComponent({
  name: "IndexPage",
  setup() {
    const router = useRouter();
    const route = useRoute();
    const userStore = useUserStore();
    const systemStore = useSystemStore();

    const open = ref(false);
    const loading = ref(false);
    const tabKey = ref(0);
    const coursesList = ref<CourseModel[]>([]);
    const categories = ref<CategoryModel[]>([]);
    const categoryId = ref(0);
    const categoryText = ref("所有分类");
    const selectKey = ref([0]);
    const learnCourseRecords = ref<LearnCourseRecordsModel>({});
    const learnCourseHourCount = ref<any>({});
    const stats = ref<StatsModel | null>(null);
    const resourceUrl = ref<ResourceUrlModel>({});

    const systemConfig = computed(() => systemStore);
    const currentDepId = computed(() => userStore.currentDepId);

    onMounted(() => {
      getParams();
      const result = new URLSearchParams(route.query as any);
      tabKey.value = Number(result.get("tab") || 0);
      categoryId.value = Number(result.get("cid") || 0);
      categoryText.value = String(result.get("catName") || "所有分类");
      selectKey.value = [Number(result.get("cid") || 0)];

      if (currentDepId.value !== 0) {
        getData();
      }
    });

    watch(
      () => route.query,
      (newQuery) => {
        const result = new URLSearchParams(newQuery as any);
        tabKey.value = Number(result.get("tab") || 0);
        categoryId.value = Number(result.get("cid") || 0);
        categoryText.value = String(result.get("catName") || "所有分类");
        selectKey.value = [Number(result.get("cid") || 0)];
      }
    );

    watch([tabKey, currentDepId, categoryId], () => {
      if (currentDepId.value === 0) {
        return;
      }
      getData();
    });

    watch(
      () => systemConfig.value.systemName,
      (newName) => {
        if (newName) {
          document.title = newName || "首页";
        }
      }
    );

    const hide = () => {
      open.value = false;
    };

    const getData = () => {
      loading.value = true;
      user.courses(currentDepId.value, categoryId.value).then((res: any) => {
        const records: LearnCourseRecordsModel = res.data.learn_course_records;
        stats.value = res.data.stats;
        learnCourseRecords.value = records;
        learnCourseHourCount.value = res.data.user_course_hour_count;
        resourceUrl.value = res.data.resource_url;

        if (tabKey.value === 0) {
          coursesList.value = res.data.courses;
        } else if (tabKey.value === 1) {
          const arr: CourseModel[] = [];
          res.data.courses.map((item: any) => {
            if (item.is_required === 1) {
              arr.push(item);
            }
          });
          coursesList.value = arr;
        } else if (tabKey.value === 2) {
          const arr: CourseModel[] = [];
          res.data.courses.map((item: any) => {
            if (item.is_required === 0) {
              arr.push(item);
            }
          });
          coursesList.value = arr;
        } else if (tabKey.value === 3) {
          const arr: CourseModel[] = [];
          res.data.courses.map((item: any) => {
            if (records[item.id] && records[item.id].progress >= 10000) {
              arr.push(item);
            }
          });
          coursesList.value = arr;
        } else if (tabKey.value === 4) {
          const arr: CourseModel[] = [];
          res.data.courses.map((item: any) => {
            if (!records[item.id] || (records[item.id] && records[item.id].progress < 10000)) {
              arr.push(item);
            }
          });
          coursesList.value = arr;
        }
        loading.value = false;
      });
    };

    const getParams = () => {
      user.coursesCategories().then((res: any) => {
        const categoriesData = res.data.categories;
        if (JSON.stringify(categoriesData) !== "{}") {
          const new_arr: CategoryModel[] = checkArr(categoriesData, 0);
          new_arr.unshift({
            key: 0,
            title: "所有分类",
          });
          categories.value = new_arr;
        }
      });
    };

    const checkArr = (categoriesData: any[], id: number) => {
      const arr: CategoryModel[] = [];
      for (let i = 0; i < categoriesData[id].length; i++) {
        if (!categoriesData[categoriesData[id][i].id]) {
          arr.push({
            title: <span style={{ marginRight: 20 }}>{categoriesData[id][i].name}</span>,
            key: categoriesData[id][i].id,
          });
        } else {
          const new_arr: CategoryModel[] = checkArr(categoriesData, categoriesData[id][i].id);
          arr.push({
            title: <span style={{ marginRight: 20 }}>{categoriesData[id][i].name}</span>,
            key: categoriesData[id][i].id,
            children: new_arr,
          });
        }
      }
      return arr;
    };

    const items = [
      {
        key: 0,
        label: "全部",
      },
      {
        key: 1,
        label: "必修课",
      },
      {
        key: 2,
        label: "选修课",
      },
      {
        key: 3,
        label: "已学完",
      },
      {
        key: 4,
        label: "未学完",
      },
    ];

    const onChange = (key: number) => {
      tabKey.value = key;
      router.push("/?cid=" + categoryId.value + "&catName=" + categoryText.value + "&tab=" + key);
    };

    const onSelect = (selectedKeys: any, info: any) => {
      categoryId.value = selectedKeys[0];
      if (info.node.key === 0) {
        categoryText.value = info.node.title;
        selectKey.value = selectedKeys;
        hide();
        router.push("/?cid=" + selectedKeys[0] + "&catName=" + info.node.title + "&tab=" + tabKey.value);
      } else {
        categoryText.value = info.node.title.children[0].children;
        selectKey.value = selectedKeys;
        hide();
        router.push("/?cid=" + selectedKeys[0] + "&catName=" + info.node.title.children[0].children + "&tab=" + tabKey.value);
      }
    };

    const handleOpenChange = (newOpen: boolean) => {
      open.value = newOpen;
    };

    const dropItem = () => (
      <div
        style={{
          maxHeight: 600,
          overflowX: "hidden",
          overflowY: "auto",
        }}
      >
        <Tree selectedKeys={selectKey.value} switcherIcon={null} onSelect={onSelect} treeData={categories.value} blockNode defaultExpandAll={true} />
      </div>
    );

    return () => (
      <div class="main-body">
        <div class="content">
          <div class={styles["top-cont"]}>
            <div class={styles["top-item"]}>
              <div class={styles["title"]}>
                <img class={styles["icon"]} src={myLesoon} />
                <span>课程进度</span>
              </div>
              <div class={styles["info"]}>
                <div class={styles["info-item"]}>
                  <span>必修课：已学完课程</span>
                  <strong> {stats.value?.required_finished_course_count || 0} </strong>
                  <span>/ {stats.value?.required_course_count || 0}</span>
                </div>
                {stats.value && stats.value.nun_required_course_count > 0 && (
                  <div class={styles["info-item"]}>
                    <span>选修课：已学完课程</span>
                    <strong> {stats.value?.nun_required_finished_course_count || 0} </strong>
                    <span>/ {stats.value?.nun_required_course_count || 0}</span>
                  </div>
                )}
              </div>
            </div>
            <div class={styles["top-item"]}>
              <div class={styles["title"]}>
                <img class={styles["icon"]} src={studyTime} />
                <span>学习时长</span>
              </div>
              {stats.value ? (
                <div class={styles["info"]}>
                  <div class={styles["info-item"]}>
                    今日：
                    {studyTimeFormat(stats.value.today_learn_duration)[0] !== 0 && (
                      <>
                        <strong> {studyTimeFormat(stats.value.today_learn_duration)[0] || 0} </strong>
                        小时
                      </>
                    )}
                    <strong> {studyTimeFormat(stats.value.today_learn_duration)[1] || 0} </strong>
                    分钟
                  </div>
                  <div class={styles["info-item"]}>
                    累计：
                    {studyTimeFormat(stats.value.learn_duration || 0)[0] !== 0 && (
                      <>
                        <strong> {studyTimeFormat(stats.value.learn_duration || 0)[0] || 0} </strong>
                        小时
                      </>
                    )}
                    <strong> {studyTimeFormat(stats.value.learn_duration || 0)[1] || 0} </strong>
                    分钟
                  </div>
                </div>
              ) : null}
            </div>
          </div>
          <div class={styles["tabs"]}>
            {items.map((item: any) => (
              <div
                key={item.key}
                class={item.key === tabKey.value ? styles["tab-active-item"] : styles["tab-item"]}
                onClick={() => {
                  onChange(item.key);
                }}
              >
                <div class={styles["tit"]}>{item.label}</div>
                {item.key === tabKey.value && <Image class={styles["banner"]} width={40} height={8} preview={false} src={iconRoute} style={{ marginTop: -16 }} />}
              </div>
            ))}
            <Popover content={dropItem()} placement="bottomRight" open={open.value} trigger="click" onOpenChange={handleOpenChange}>
              <Space class={styles["dropButton"]}>
                {categoryText.value}
                <i class="iconfont icon-icon-xiala" style={{ fontSize: 16 }} />
              </Space>
            </Popover>
          </div>
          {loading.value && (
            <Row
              style={{
                width: 1200,
                margin: "0 auto",
                paddingTop: 14,
                minHeight: 301,
              }}
            >
              <div class="float-left d-j-flex mt-50">
                <Spin size="large" />
              </div>
            </Row>
          )}

          {!loading.value && coursesList.value.length === 0 && (
            <Row
              style={{
                width: 1200,
                margin: "0 auto",
                paddingTop: 14,
                minHeight: 301,
              }}
            >
              <Col span={24}>
                <Empty />
              </Col>
            </Row>
          )}
          {!loading.value && coursesList.value.length > 0 && (
            <div class={styles["courses-list"]}>
              {coursesList.value.map((item: any) => (
                <div key={item.id}>
                  {learnCourseRecords.value[item.id] && (
                    <CoursesModel
                      id={item.id}
                      title={item.title}
                      thumb={item.thumb === -1 ? defaultThumb1 : item.thumb === -2 ? defaultThumb2 : item.thumb === -3 ? defaultThumb3 : resourceUrl.value[item.thumb]}
                      isRequired={item.is_required}
                      progress={Math.floor(learnCourseRecords.value[item.id].progress / 100)}
                    />
                  )}

                  {!learnCourseRecords.value[item.id] && learnCourseHourCount.value[item.id] && learnCourseHourCount.value[item.id] > 0 && (
                    <CoursesModel
                      id={item.id}
                      title={item.title}
                      thumb={item.thumb === -1 ? defaultThumb1 : item.thumb === -2 ? defaultThumb2 : item.thumb === -3 ? defaultThumb3 : resourceUrl.value[item.thumb]}
                      isRequired={item.is_required}
                      progress={1}
                    />
                  )}
                  {!learnCourseRecords.value[item.id] && !learnCourseHourCount.value[item.id] && (
                    <CoursesModel
                      id={item.id}
                      title={item.title}
                      thumb={item.thumb === -1 ? defaultThumb1 : item.thumb === -2 ? defaultThumb2 : item.thumb === -3 ? defaultThumb3 : resourceUrl.value[item.thumb]}
                      isRequired={item.is_required}
                      progress={0}
                    />
                  )}
                </div>
              ))}
            </div>
          )}
        </div>
        <div class={styles["extra"]}>{systemConfig.value.pcIndexFooterMsg}</div>
      </div>
    );
  },
});
